<script lang="ts" setup generic="T extends BaseEntity">
import {
  activeById,
  dateTimeToDate,
  hasPermission,
  isAdmin,
  isLoginUserById,
  isSuperAdmin,
  logicalDeleteById,
  physicalDeleteById
} from '@/index';
import type { BaseEntity } from '@/index.d';
import { type ElTable } from 'element-plus';
import { useWindowSize } from '@vueuse/core';

const { width } = useWindowSize();

const tableRef = useTemplateRef<InstanceType<typeof ElTable>>('tableRef');
const props = defineProps({
  height: Number,
  tableData: Array,
  rowSelected: Array<T>,
  selection: { type: Boolean, default: false },
  title: { type: String, required: true },
  baseUrl: { type: String, required: true },
  loading: { type: Boolean, default: false },
  logicDelete: { type: Boolean, default: false },
  id: { type: Boolean, default: false },
  version: { type: Boolean, default: false },
  operateRecord: { type: Boolean, default: false },
  operateColumn: { type: Boolean, default: false },
  defaultExpandAll: { type: Boolean, default: false }
});

const emit = defineEmits<{
  (e: 'handleView', row: any): void;
  (e: 'handleUpdate', row: T): void;
  (e: 'handleRowClick', row: T): void;
  (e: 'handleReload'): void;
}>();

const handleDelete = async (id: number) => {
  const res = await physicalDeleteById(props.baseUrl, id);
  res && emit('handleReload');
};

const handleLogicDelete = async (row: T) => {
  if (row.deleted) {
    const res = await logicalDeleteById(props.baseUrl, row.id as number);
    res && emit('handleReload');
  } else {
    const res = await activeById(props.baseUrl, row.id as number);
    res && emit('handleReload');
  }
};

const handleRowClick = (row: T) => emit('handleRowClick', row);

watch(
  () => props.rowSelected,
  value => {
    value?.forEach(item => tableRef.value?.toggleRowSelection(item, true));
  }
);
</script>
<template>
  <el-table
    ref="tableRef"
    :data="props.tableData"
    :height
    v-loading="loading"
    highlight-current-row
    v-bind="$attrs"
    stripe
    border
    fit
    @row-click="handleRowClick"
    :default-expand-all="defaultExpandAll"
  >
    <el-table-column v-if="selection" type="selection" width="55" />
    <slot name="columns"></slot>
    <hq-table-column
      v-if="isAdmin() && props.id"
      prop="id"
      label="id"
      width="150px"
      align="center"
    />
    <hq-table-column
      v-if="isAdmin() && props.version"
      prop="version"
      label="version"
      width="150px"
      align="center"
    />
    <hq-table-column
      v-if="isAdmin() && props.operateRecord"
      prop="creator.name"
      label="创建人员"
      width="150px"
      align="center"
    />
    <el-table-column
      v-if="isAdmin() && props.operateRecord"
      label="创建日期"
      width="150px"
      align="center"
      :formatter="row => dateTimeToDate(row.createTime as string)"
    />
    <hq-table-column
      v-if="isAdmin() && props.operateRecord"
      prop="updater.name"
      label="更新人员"
      width="150px"
      align="center"
    />
    <el-table-column
      v-if="isAdmin() && props.operateRecord"
      label="更新日期"
      width="150px"
      align="center"
      :formatter="row => dateTimeToDate(row.updateTime as string)"
    />
    <hq-table-column
      label="状态"
      fixed="right"
      width="150px"
      v-if="logicDelete && hasPermission(`逻辑删除${title}`)"
    >
      <template #default="{ row }">
        <el-switch
          v-model="row.deleted"
          active-text="激活"
          inactive-text="停用"
          :active-value="false"
          :inactive-value="true"
          size="small"
          @change="handleLogicDelete(row)"
          v-if="isLoginUserById(row.creatorId)"
        />
      </template>
    </hq-table-column>
    <hq-table-column
      label="操作"
      fixed="right"
      width="150px"
      align="left"
      v-if="props.operateColumn && width > 1000"
    >
      <template #default="{ row }">
        <el-button link type="primary" size="small" @click="$emit('handleView', row)">
          <!-- v-button="`查看${props.title}`" -->
          查看
        </el-button>
        <el-button
          link
          type="warning"
          size="small"
          @click="$emit('handleUpdate', row)"
          v-if="isLoginUserById(row.creatorId) && hasPermission(`修改${title}`)"
        >
          修改
        </el-button>
        <el-popconfirm
          hide-icon
          :hide-after="0"
          confirm-button-text="确认"
          cancel-button-text="取消"
          title="确认删除吗？"
          @confirm="handleDelete(row.id)"
          v-if="isSuperAdmin()"
        >
          <template #reference>
            <el-button link type="danger" size="small">删除</el-button>
          </template>
        </el-popconfirm>
      </template>
    </hq-table-column>
    <hq-table-column label="操作" :min-width="100" v-else-if="props.operateColumn">
      <template #default="{ row }">
        <el-button link type="primary" size="small" @click="$emit('handleView', row)">
          <!-- v-button="`查看${props.title}`" -->
          查看
        </el-button>
        <el-button
          link
          type="warning"
          size="small"
          @click="$emit('handleUpdate', row)"
          v-if="isLoginUserById(row.creatorId) && hasPermission(`修改${title}`)"
        >
          修改
        </el-button>
        <el-popconfirm
          hide-icon
          :hide-after="0"
          confirm-button-text="确认"
          cancel-button-text="取消"
          title="确认删除吗？"
          @confirm="handleDelete(row.id)"
          v-if="isSuperAdmin()"
        >
          <template #reference>
            <el-button link type="danger" size="small">删除</el-button>
          </template>
        </el-popconfirm>
      </template>
    </hq-table-column>
  </el-table>
</template>
<style lang="scss" scoped></style>
